(function(lib, undefined) {
    lib.JS={};
    lib.JS.login = {
        init:function() {
            var _this=this;
            _this.initHeadInfo();

            $('#J_login').click(function() {
                _this.getLogin();
            });
            $('#J_logout').click(function(){
                _this.logout();
            });
        },
        getLogin:function (event) {
            var data={
                'username' : $('#username').val(),
                'password' : $('#password').val()
            };
            $.ajax({
                method : 'post',
                url : '/login',
                data:data
            }).success(function(resp){
                console.log(resp.status);
                if(resp.status===0){
                    var resultData = resp.result;
                    if(resultData){
                        // 写cookie  data.name
                        JS.COOKIE.addCookie("userid", resultData.result.user.userid, JS.COOKIE.timeOut);
                        JS.COOKIE.addCookie("username", resultData.result.user.username, JS.COOKIE.timeOut);
                        $("#loginMsg").hide();
                    }else{
                        $("#loginMsg").show();
                    }
                    window.location.href="/";
                }else if(resp.status === 2){
                    alert('用户名或密码错误');
                }else{
                    alert(resp.message);
                }
            }).error(function() {
                alert('登录失败');
            });
        },
        logout:function () {
            $.ajax({
                method : 'get',
                url : '/logout'
            }).success(function(resp){
                console.log(resp.status);
                if(resp.status===1){
                    window.location.href="/";
                }
            }).error(function() {
                alert('登录失败');
            });
        },
        initHeadInfo:function () {
            var username = JS.COOKIE.getCookie('username');
            $(".J_username").html("<a id='loginless'>您好，"+username+"</a>");
        }
    };

    JS.COOKIE = {
        domainName: "localhost", // .ruixuesoft.com
        timeOut: (90 * 24 * 60 * 60),
        Trim: function(str) {
            str = JS.COOKIE.replaceNullOrUndifined(str);
            var iStart = 0;
            var iEnd = 0;
            var iLen = str.length;
            for (iStart = 0; iStart < iLen && str.charAt(iStart) == " "; iStart++);
            for (iEnd = iLen; iEnd > 1 && str.charAt(iEnd - 1) == "  "; iEnd--);
            if (iStart > iEnd) return "";
            return str.substring(iStart, iEnd);
        },
        TrimQuotationMarks: function(str) {
            str = JS.COOKIE.replaceNullOrUndifined(str);
            var iStart = 0;
            var iEnd = str.length;
            if (str.charAt(iEnd - 1) == '"') iEnd--;
            if (str.charAt(0) == '"') iStart++;
            if (iStart > iEnd) return "";
            return str.substring(iStart, iEnd);
        },
        replaceNullOrUndifined: function(data) {
            if (data == null || typeof data == 'undefined')
                return "";
            return data;
        },
        getCookie: function(objName) {
            try {
                var cookies = document.cookie.split(";");
                var iLen = cookies.length;
                if (iLen <= 0)
                    return null;
                var keyName = JS.COOKIE.Trim(objName);
                for (var i = 0; i < iLen; i++) {
                    if (typeof cookies[i] == 'undefined' || cookies[i] == "")
                        continue;
                    var keyValues = cookies[i].split("=");
                    var key = JS.COOKIE.Trim(keyValues[0]);
                    if (key == keyName) {
                        return decodeURIComponent(JS.COOKIE.TrimQuotationMarks(JS.COOKIE.Trim(keyValues[1]))).replace(/%20/g, " ");
                    }
                }
            } catch (e) {

            }
            return null;
        },
        deleteCookie: function(deleteCPS) {
            document.cookie = null;
        },
        clearCookie: function() {
            var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
            if (keys) {
                for (var i = keys.length; i--;)
                    document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString();
            }
        },
        addCookie: function(objName, objValue, objSeconds, secureFlag, othenDomainName) {
            var str = objName + "=" + encodeURIComponent(objValue);
            if (objSeconds != 0) {
                var date = new Date();
                var ms = objSeconds * 1000;
                date.setTime(date.getTime() + ms);
                str += "; expires=" + date.toGMTString();
            }
            str += "; path=/";
            if (othenDomainName == null || othenDomainName == typeof("undifined")) {
                str += "; domain=" + JS.COOKIE.domainName;
            } else {
                str += "; domain=" + othenDomainName;
            }
            if (typeof secureFlag != 'undefined' && secureFlag) {
                str += "; secure";
            }
            document.cookie = str;
        }
    };

    lib.JS.AJAX=function(url,options,callback){
        var _this = this;
        var ajaxObj=null;

        if(options.sendTimeout){
            timeoutId = window.setTimeout(function(){ajaxObj.abort();if(callback) callback.call(_this,{status:"timeout"});alert("请求超时，请稍后再试！");},options.timeout||10000);
        }

        var urlParam=(options.param||($.type(options)=="string"?options:''));
        if(options.type && options.type=="post"){
            urlParam = options.param;
        }

        ajaxObj = $.ajax({
            type: options.type||"get",
            url: url,
            async:options.async===false?false:true,
            context:options.context||_this,
            data: urlParam+format,
            dataType: options.dataType||"jsonp",
            crossDomain:true,
            success:function(resultData,textStatus){
                if(resultData.status == "0"){
                    if(callback){
                        callback.call(options.context||_this, resultData, options.extData);
                    }
                }
                else if(resultData.status == "1"){
                    alert(resultData.message);
                }
                else if(resultData.status == "2"){
                    JS.COOKIE.clearCookie();
                    alert("用户名或密码错误！");
                }
                else{
                    alert(resultData.message);
                }
            },error:function(xhr, textStatus, errorThrown){
                if(xhr.status==400) JS.COOKIE.clearCookie();
                if(callback)
                    callback.call(_this,{status:"error",message:textStatus});
            }
        });
    };

    lib.JS.Tools = {
        includeJS: function(fileUrl, callback, params) {
            if (typeof _3rdres == 'undefined') {
                _3rdres = {};
            }
            if (_3rdres[fileUrl]) {
                return;
            }
            _3rdres[fileUrl] = 'loading';
            setTimeout(function() {
                var oHead = document.getElementsByTagName('HEAD').item(0);
                var oScript = document.createElement("script");
                oScript.language = "javascript";
                oScript.type = "text/javascript";
                oScript.defer = true;
                oScript.async = true;
                oScript.src = fileUrl;

                var _callback = function() {
                    _3rdres[this.src] = true;
                    if (typeof callback == 'function') {
                        callback.call(this);
                    }
                };
                if (typeof params != "undefined") {
                    for (var ps in params) {
                        oScript[ps] = params[ps];
                        oScript.setAttribute(ps, params[ps]);
                    }
                }
                oHead.appendChild(oScript);
                oScript.onload = _callback;
                oScript.onreadystatechange = _callback;
            }, 0);
            return true;
        },
        fmoney:function (s, n){
            n = n > 0 && n <= 20 ? n : 2;
            s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
            var l = s.split(".")[0].split("").reverse(),
                r = s.split(".")[1];
            t = "";
            for(i = 0; i < l.length; i ++ )
            {
                t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
            }
            return t.split("").reverse().join("") + "." + r;
        },
        getCurrentDate: function() {
            return new Date().getTime();
        },
        getNowFormatDate: function() {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
                " " + date.getHours() + seperator2 + date.getMinutes() +
                seperator2 + date.getSeconds();
            return currentdate;
        },
        getParameterByName: function(name) {
            var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
            return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
        },
        template: function(id, data) {
            return this.trim(window.template(id, data), "");
        },
        trim: function(str, is_global) {
            var result;
            result = str.replace(/(^\s+)|(\s+$)/g, "");
            if (is_global.toLowerCase() == "g") result = result.replace(/\s/g, "");
            return result;
        },
        jsonToString: function(json) {
            var strTemp = "";
            for (var key in json) {
                strTemp += key + '=' + json[key] + '&';
            }
            return strTemp.slice(0, -1);
        },
        stringToJson: function(string) {
            var tempURL = string.split('&');
            var json = "";
            for (var i = 0; i < tempURL.length; i++) {
                var t = tempURL[i].split('=');
                json += "'" + t[0] + "':'" + t[1] + "',";
            }
            return eval("({" + json.substring(0, json.length - 1) + "})");
        },
        textEllipsis: function(text, count) {
            if (text.length <= count)
                return text;
            else
                return text.substring(0, count) + "...";
        },
        winWidth: function() { //当前窗口的width
            var width;
            if (window.innerWidth) {
                width = window.innerWidth;
            } else if ((document.body) && (document.body.clientWidth)) {
                width = document.body.clientWidth;
            }
            if (document.documentElement && document.documentElement.clientWidth) {
                width = document.documentElement.clientWidth;
            }
            return width;
        },
        winHeight: function() { //当前窗口的height
            return $(window).height();
        },
        getScrollTop: function() {
            // console.log(window.pageYOffset+"  "+document.body.scrollTop+"  "+document.documentElement.scrollTop,$.browser);
            return document.documentElement.scrollTop;
        },
        isEmptyObject: function(O) {
            for (var x in O) {
                return false;
            }
            return true;
        },
        getShadeLayer: function(layerClass, css, id) {
            var window_width = document.documentElement.scrollWidth || $('body').outerWidth();
            var window_height = $('html').outerHeight() > JS.Tools.winHeight() ? $('html').outerHeight() : JS.Tools.winHeight();
            return '<div id="' + (id || "shadeLayer") + '" class="' + layerClass + '" style="width:' + window_width + 'px;height:' + window_height + 'px;*background: #000000;_background: #000000;' + (css || "") + '"></div>';
        },
        moveBox: function(obj) {
            var $cartFly = $(obj).parent().find("img");
            $cartFly.each(function() {
                if (typeof $(this).attr("alt") != "undefined" && $(this).attr("alt") != "") {
                    $cartFly = $(this);
                }
            });

            var divTop = $cartFly.offset().top;
            var divLeft = $cartFly.offset().left;
            var tmp = $cartFly.clone(true);
            if (!$cartFly.is(":animated")) {
                $(obj).parent().find(".cartFly").prepend(tmp);
                $cartFly.css({
                    "position": "absolute",
                    "z-index": "201110",
                    "left": divLeft + "px",
                    "top": divTop + "px"
                });
                $cartFly.animate({
                    "left": ($("#collectBox").offset().left - $("#collectBox").width()) + "px",
                    "top": ($(document).scrollTop() + 30) + "px",
                    "width": parseInt($cartFly.css("width")) / 5,
                    "height": parseInt($cartFly.css("height")) / 5
                }, 500, function() {
                    $cartFly.animate({
                        "left": $("#collectBox").offset().left + "px",
                        "top": $("#collectBox").offset().top + "px"
                    }, 500, function() {
                        $cartFly.remove();
                    }).fadeTo(0, 0.1).hide(0);
                });
            }

        },
        setEleToCenter: function(eleId, content) {
            content = content || {};
            var width = $(eleId).outerWidth();
            var height = $(eleId).outerHeight();
            $(eleId).css("left", content.x || (JS.Tools.winWidth() / 2 - width / 2 + (content.offsetX || 0)));
            var y = content.offsetY || 0;
            y += JS.Tools.winHeight() / 2 - height / 2;
            $(eleId).css("position", "fixed");
            y -= 30;
            $(eleId).css("top", content.y || y < 0 ? 10 : y);
        },
        pointerInElement: function(ele, parm) {
            parm = parm || {};
            $("body").unbind("mousemove").mousemove(function(e) {
                if ($(ele).is(":hidden") || $(ele).length === 0) {
                    $(this).unbind("mousemove");
                } else {
                    var o = $(ele).offset(),
                        x = e.clientX,
                        y = e.clientY,
                        left = o.left - $(window).scrollLeft() + (parm.offsetX || 0),
                        top = o.top - $(window).scrollTop() + (parm.offsetY || 0),
                        w = $(ele).width() + (parm.offsetWidth || 0),
                        h = $(ele).height() + (parm.offsetHeight || 0);

                    if (y < top || y > (h + top) || x > left + w || x < left) {
                        $(this).unbind("mousemove");
                        if (parm.callback)
                            parm.callback(false);
                    } else {
                        if (parm.callback)
                            parm.callback(true);
                    }
                }
            });
        }
    };

    $.fn.extend({
        fixIE6Pos: function(maxTop) {
            var t = this.offset().top,
                h = this.outerHeight(),
                cssTop = parseInt(this.css("top").slice(0, -2)),
                _this = this;

            var maxTop = maxTop || $("body").height();
            if ($.type(maxTop) == "string") {
                maxTop = $(maxTop).offset().top;
            }
            maxTop = parseInt(maxTop - h);
            if ($.browser.msie && $.browser.version == "6.0") {
                this.css("position", "absolute");
                $(window).scroll(function() {
                    var offsetTop = t + $(window).scrollTop();
                    if (offsetTop < maxTop) {
                        _this.stop();
                        _this.animate({
                            "top": offsetTop + "px"
                        }, 1000);
                    }
                });
            } else {
                $(window).scroll(function() {
                    if (parseInt($(window).scrollTop() + cssTop) > maxTop) {
                        if (_this.css("position") != "absolute") {
                            _this.css("position", "absolute");
                            _this.css("top", $(window).scrollTop());
                        }
                    } else {
                        _this.css("position", "fixed");
                        _this.css("top", cssTop);
                    }
                });
            }
        },
        autoscroll: function() {
            $('html,body').animate({
                    scrollTop: $(this).offset().top
                },
                500
            );
        },
        center: function() {
            this.css('position', 'absolute');
            this.css('top', ($(window).height() - this.height()) / +$(window).scrollTop() + 'px');
            this.css('left', ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + 'px');
            return this;
        }
    });

    lib.JS.getMoveAction=function(moveBody){
        var isMove=false;
        var lastX=-1,lastY=-1;
        var offsetX=-1,offsetY=-1;
        $(".moveBar").css("cursor","move");
        $(".moveBar").unbind("mousedown").bind("mousedown",function(event){
            event.preventDefault();
            isMove=true;
            lastX = event.clientX;
            lastY = event.clientY;
            var body = $(moveBody);
            var tempX = body.offset().left;
            var tempY = body.offset().top-JS.Tools.getScrollTop();
            offsetX = event.clientX - tempX;
            offsetY = event.clientY - tempY;
            $("body").unbind("mousemove").bind("mousemove",function(event){
                if(!isMove)
                    return false;
                event.preventDefault();
                event.stopPropagation();
                lastX = event.clientX-lastX;
                lastY = event.clientY-lastY;

                body.css("left",event.clientX-lastX-offsetX);
                body.css("top",event.clientY-lastY-offsetY);
                lastX= event.clientX;
                lastY= event.clientY;
            });
        }).unbind("mouseup").bind("mouseup",function(event){
            isMove=false;
            $("body").unbind("mousemove");
        });
        $("body").unbind("mouseup").bind("mouseup",function(){
            isMove=false;
        });
        $(".moveBar").blur(function(){
            isMove=false;
            $("body").unbind("mousemove");
        });
    };
    lib.JS.widget = {
        loadView: function(options) {
            var id = options.id || options;
            var width = $(id).width();
            var allWidth = width * (options.frame || 12);
            var currY = 0;
            var intervalId;
            intervalId = setInterval(function() {
                if ($(id).length === 0 || $(id).is(":hidden")) {
                    clearInterval(intervalId);
                }
                $(id).css("background-position", currY + "px 0px");
                currY -= width;
                if (currY == -allWidth)
                    currY = 0;
            }, options.flash || 100);
        },
        popAni: function(id) {
            var o = $(id),
                oTop = o.css("top") || o.scrollTop() || "0px";
            var top = parseInt(oTop.slice(0, -2));
            o.css("opacity", 0);
            o.stop().animate({
                "opacity": 1,
                "top": top + 30
            }, 400);
        },
        closeAni: function(id, callback) {
            var o = $(id),
                oTop = o.css("top") || o.scrollTop() || "0px";
            var top = parseInt(oTop.slice(0, -2));
            $("#shadeLayer").animate({
                "opacity": 0
            }, 200);
            o.stop().animate({
                "opacity": 0,
                "top": top - 30
            }, 300, callback);
        }
    };

    window.alert = function(content, callback, opts) {
        if (!$.isFunction(callback) && $.type(callback) == "object")
            opts = callback;
        opts = opts || {};
        $(".calert").remove();
        var temp = JS.Tools.getShadeLayer("calert") +
            "<div id='alert-body' class='calert'>" +
            "<div id='alert-title' class='moveBar'>" +
            (content.title || "") + "<a id='alert-close'>X</a>" +
            "</div>" +
            "<div id='alert-content'>" +
            (content.body || content) +
            "</div>" +
            "</div>";
        $("body").append(temp);

        if (content.countdown) {
            content.timeCountdown = content.timeCountdown || 10;
            $("#timeCountdown").text(content.timeCountdown);
            content.timeCountdownId = window.setInterval(function() {
                if (content.timeCountdown > 1) {
                    content.timeCountdown -= 1;
                    $("#timeCountdown").text(content.timeCountdown);
                } else {
                    window.clearInterval(content.timeCountdownId);
                    $("#alert-close").trigger("click");
                }
            }, 1000);
            $("#alert-body").mouseenter(function() {
                $("#countdownContainer").remove();
                window.clearInterval(content.timeCountdownId);
            });
        }

        JS.Tools.setEleToCenter("#alert-body", {
            offsetY: -100
        });
        JS.widget.popAni("#alert-body");
        if (opts.layerClick) {
            $("#shadeLayer").unbind("click").click(function() {
                $("#alert-close").trigger("click");
            });
        }
        $("#alert-close").unbind("click").click(function() {
            JS.widget.closeAni("#alert-body", function() {
                $(".calert").remove();
                if (typeof callback != "undefined" && $.isFunction(callback))
                    callback();
            });
        });
        JS.getMoveAction("#alert-body");
    };
    window.myConfirm = function(content, callback, opts) {
        if (!$.isFunction(callback) && $.type(callback) == "object")
            opts = callback;
        opts = opts || {};

        $(".comfirm").remove();
        var window_height = $('body').height() > JS.Tools.winHeight() ? $('body').height() : JS.Tools.winHeight();
        var temp = JS.Tools.getShadeLayer("comfirm") +
            "<div id='confirm-body' class='comfirm'>" +
            "<div id='alert-title' class='moveBar'>" +
            (content.title || "") + "<a id='alert-close'>X</a>" +
            "</div>" +
            "<div id='confirm-content'>" +
            (content.body || content) +
            "</div>" +
            "<div id='confirm-footer'>" +
            "<span id='confirm-ok' class='confirm-button'>" + (content.okText || "确定") + "</span><span id='confirm-cancel' class='confirm-button' style='margin-left:50px'>取消</span>" +
            "</div>" +
            "</div>";
        $("body").append(temp);
        JS.Tools.setEleToCenter("#confirm-body");
        JS.widget.popAni("#confirm-body");

        $("#alert-close,#confirm-cancel").unbind("click").click(function() {
            JS.widget.closeAni("#confirm-body", function() {
                $(".comfirm").remove();
                if ($.isFunction(callback))
                    callback(false);
            });
        });
        if (opts.layerClick) {
            $("#shadeLayer").unbind("click").click(function() {
                $("#alert-close").trigger("click");
            });
        }
        $("#confirm-ok").unbind("click").click(function() {
            JS.widget.closeAni("#confirm-body", function() {
                $(".comfirm").remove();
                if ($.isFunction(callback))
                    callback(true);
            });
        });
        JS.getMoveAction("#confirm-body");
    };
    window.pop = function(content, callback, opts) {
        if (!$.isFunction(callback) && $.type(callback) == "object")
            opts = callback;
        opts = opts || {};

        $(".pop").stop().remove();
        var htmlText = content;
        isId = /^\#/.test(htmlText);
        if (isId) {
            htmlText = document.getElementById(htmlText.substring(1, htmlText.length)).outerHTML;
            if (opts.removeAfterShow)
                $(content).remove();
        }
        var temp = JS.Tools.getShadeLayer("pop", "", "popShadeLayer") +
            "<div id='pop-body' class='pop'>" +
            htmlText +
            "</div>";
        $("body").append(temp);
        if (isId)
            $("#pop-body").children().show();
        if ($.browser.msie) {
            $("#pop-body").width($("#pop-body").children().width());
        }
        JS.Tools.setEleToCenter("#pop-body");
        if (opts.x) {
            $("#pop-body").css("left", opts.x);
        }
        if (opts.y) {
            $("#pop-body").css("top", opts.y);
        }

        JS.widget.popAni("#pop-body");
        if (opts.layerClick) {
            $("#popShadeLayer").unbind("click").click(function() {
                $("#pop-close").trigger("click");
            });
        }
        if (opts.overflow) {
            document.documentElement.style.overflow = 'hidden';
        }
        $("#pop-close").die("click").live("click", function() {
            JS.widget.closeAni("#pop-body", function() {
                $(".pop").remove();
            });
            if ($.isFunction(callback)) callback();
        });
        return {
            close: function() {
                JS.widget.closeAni("#pop-body", function() {
                    $(".pop").remove();
                });
            },
            open: function() {
                pop(htmlText, callback, opts);
                $("#pop-body").children().show();
            }
        };
    };
})(window);
$(function(){JS.login.init();});